import java.util.*;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-39-组合总和
 * @date 2025/5/6 10:23
 */
public class Solution39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(candidates, target, path, ans, 0);
        return ans;
    }

    private void dfs(int[] candidates, int target, List<Integer> path, List<List<Integer>> ans, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<>(path));
            return;
        }
        // 选择下一个数,逐渐往下构造递归树
        dfs(candidates, target, path, ans, idx + 1);
        // 选择当前的数,idx保持不变
        if (target - candidates[idx] >= 0) {
            path.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], path, ans, idx);
            path.remove(path.size() - 1); // 恢复现场
        }
    }
}
